<template>
  <div class="space-y-6">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">评论管理</h2>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <el-input
          v-model="searchForm.bookTitle"
          placeholder="图书标题"
          clearable
        >
          <template #prefix>
            <i class="fas fa-book text-gray-400"></i>
          </template>
        </el-input>
        <el-input
          v-model="searchForm.userName"
          placeholder="用户名"
          clearable
        >
          <template #prefix>
            <i class="fas fa-user text-gray-400"></i>
          </template>
        </el-input>
        <el-select v-model="searchForm.rating" placeholder="评分" clearable>
          <el-option label="全部评分" value=""></el-option>
          <el-option label="5星" value="5"></el-option>
          <el-option label="4星" value="4"></el-option>
          <el-option label="3星" value="3"></el-option>
          <el-option label="2星" value="2"></el-option>
          <el-option label="1星" value="1"></el-option>
        </el-select>
        <el-select v-model="searchForm.status" placeholder="状态" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option label="显示" value="1"></el-option>
          <el-option label="隐藏" value="0"></el-option>
        </el-select>
        <div class="flex space-x-2">
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="reviewList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="图书" min-width="200">
          <template #default="{ row }">
            <div class="flex items-center">
              <img :src="getImageUrl(row.bookCover)" :alt="row.bookTitle" class="w-12 h-16 object-cover rounded mr-3" @error="handleImageError">
              <span>{{ row.bookTitle }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户" width="120" />
        <el-table-column label="评分" width="100">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-rate
                v-model="row.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评论内容" min-width="300">
          <template #default="{ row }">
            <div class="max-w-xs">
              <p class="text-sm text-gray-600 line-clamp-3">{{ row.content }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="likes" label="点赞数" width="100" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="评论时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="315" fixed="right" align="center" >
          <template #default="{ row }">
            <el-button size="small" type="success" @click="showReviewDetail(row)">
              <i class="fas fa-eye mr-1"></i>
              详情
            </el-button>
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              <i class="fas fa-edit mr-1"></i>
              编辑
            </el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleReviewStatus(row)"
            >   
              <i class="fas fa-toggle-on mr-1"></i>
              {{ row.status === 1 ? '隐藏' : '显示' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteReview(row)">
              <i class="fas fa-trash mr-1"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center py-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评论详情"
      width="700px"
    >
      <div v-if="currentReview" class="space-y-4">
        <!-- 图书信息 -->
        <div class="flex items-center p-4 bg-gray-50 rounded">
          <img :src="getImageUrl(currentReview.bookCover)" :alt="currentReview.bookTitle" class="w-16 h-20 object-cover rounded mr-4" @error="handleImageError">
          <div>
            <h4 class="font-medium text-lg">{{ currentReview.bookTitle }}</h4>
            <p class="text-gray-500">{{ currentReview.bookAuthor }}</p>
          </div>
        </div>

        <!-- 评论信息 -->
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <span class="text-gray-500 mr-2">评论用户：</span>
              <span class="font-medium">{{ currentReview.userName }}</span>
            </div>
            <div class="flex items-center">
              <span class="text-gray-500 mr-2">评分：</span>
              <el-rate
                v-model="currentReview.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}分"
              />
            </div>
          </div>
          
          <div>
            <span class="text-gray-500">评论时间：</span>
            <span>{{ formatDate(currentReview.createdAt) }}</span>
          </div>
          
          <div>
            <span class="text-gray-500">点赞数：</span>
            <span>{{ currentReview.likes }}</span>
          </div>
          
          <div>
            <span class="text-gray-500">状态：</span>
            <el-tag :type="currentReview.status === 1 ? 'success' : 'danger'">
              {{ currentReview.status === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </div>
        </div>

        <!-- 评论内容 -->
        <div>
          <h5 class="text-gray-500 mb-2">评论内容：</h5>
          <div class="p-4 bg-gray-50 rounded">
            <p class="text-gray-800 leading-relaxed">{{ currentReview.content }}</p>
          </div>
        </div>

        <!-- 回复列表 -->
        <div v-if="currentReview.replies && currentReview.replies.length > 0">
          <h5 class="text-gray-500 mb-2">回复列表：</h5>
          <div class="space-y-3">
            <div
              v-for="reply in currentReview.replies"
              :key="reply.id"
              class="p-3 bg-blue-50 rounded border-l-4 border-blue-200"
            >
              <div class="flex items-center justify-between mb-2">
                <span class="font-medium text-blue-800">{{ reply.userName }}</span>
                <span class="text-sm text-gray-500">{{ formatDate(reply.createdAt) }}</span>
              </div>
              <p class="text-gray-700">{{ reply.content }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑评论对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑评论"
      width="800px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="评论内容" prop="content" class="col-span-2">
            <el-input
              v-model="editForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入评论内容"
            />
          </el-form-item>
          <el-form-item label="评分" prop="rating">
            <el-rate
              v-model="editForm.rating"
              :max="5"
              show-score
              text-color="#ff9900"
              score-template="{value}分"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="editForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="显示"
              inactive-text="隐藏"
            />
          </el-form-item>
        </div>
        <el-form-item label="图书封面" prop="bookCover">
          <div class="cover-upload-container">
            <el-upload
              ref="editUploadRef"
              class="cover-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :on-success="handleEditCoverSuccess"
              :on-error="handleCoverError"
              :headers="uploadHeaders"
              accept="image/*"
              drag
            >
              <div v-if="editForm.bookCover" class="cover-preview">
                <img :src="getImageUrl(editForm.bookCover)" alt="封面预览" class="cover-image">
                <div class="cover-overlay">
                  <i class="fas fa-edit"></i>
                  <span>点击更换</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                <div class="text-gray-600">
                  <p class="mb-2">点击或拖拽图片到此处上传</p>
                  <p class="text-sm text-gray-500">支持 JPG、PNG、GIF 格式，文件大小不超过 2MB</p>
                </div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin.js'

const loading = ref(false)
const detailDialogVisible = ref(false)
const currentReview = ref(null)
const editDialogVisible = ref(false)
const editFormRef = ref()
const editUploadRef = ref()

const searchForm = reactive({
  bookTitle: '',
  userName: '',
  rating: '',
  status: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const reviewList = ref([])

const editForm = reactive({
  id: null,
  content: '',
  rating: 5,
  status: 1,
  bookCover: ''
})

const editFormRules = {
  content: [{ required: true, message: '请输入评论内容', trigger: 'blur' }],
  rating: [{ required: true, message: '请选择评分', trigger: 'change' }]
}

// 上传配置
const uploadAction = ref('/api/admin/upload')
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
})

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadReviewList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }

    const response = await adminAPI.getReviewList(params)
    reviewList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载评论列表失败:', error)
    ElMessage.error('加载评论列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadReviewList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    bookTitle: '',
    userName: '',
    rating: '',
    status: ''
  })
  handleSearch()
}

const showReviewDetail = (row) => {
  currentReview.value = row
  detailDialogVisible.value = true
}

const toggleReviewStatus = async (row) => {
  try {
    const action = row.status === 1 ? '隐藏' : '显示'
    await ElMessageBox.confirm(`确定要${action}这条评论吗？`, '确认操作')

    const newStatus = row.status === 1 ? 0 : 1
    await adminAPI.toggleReviewStatus(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(`评论${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const deleteReview = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '确认删除', {
      type: 'warning'
    })

    await adminAPI.deleteReview(row.id)
    ElMessage.success('评论删除成功')
    loadReviewList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const showEditDialog = (row) => {
  Object.assign(editForm, {
    id: row.id,
    content: row.content,
    rating: row.rating,
    status: row.status,
    bookCover: row.bookCover
  })
  editDialogVisible.value = true
}

const resetEditForm = () => {
  Object.assign(editForm, {
    id: null,
    content: '',
    rating: 5,
    status: 1,
    bookCover: ''
  })
  editFormRef.value?.resetFields()
}

const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()

    const response = await adminAPI.updateReview(editForm.id, editForm)
    if (response.code === 200) {
      ElMessage.success('评论更新成功')
      editDialogVisible.value = false
      loadReviewList()
    } else {
      ElMessage.error(response.message || '评论更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败：' + (error.response?.data?.message || error.message))
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadReviewList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadReviewList()
}

// 封面上传相关方法
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt20M = file.size / 1024 / 1024 < 20

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt20M) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

const handleEditCoverSuccess = (response) => {
  if (response.code === 200) {
    editForm.bookCover = response.data.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleCoverError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('封面上传失败')
}

const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  // 设置默认图片
  event.target.src = ''
}

onMounted(() => {
  loadReviewList()
})
</script>

<style scoped>
.line-clamp-3 {
  display: -webkit-box;
  /* -webkit-line-clamp: 3; */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.cover-upload-container {
  width: 100%;
}

.cover-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 180px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.cover-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.cover-preview {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  box-sizing: border-box;
}

.cover-image {
  max-width: 160px;
  max-height: 220px;
  object-fit: contain;
  border-radius: 4px;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 4px;
}

.cover-preview:hover .cover-overlay {
  opacity: 1;
}

.upload-placeholder {
  text-align: center;
  padding: 20px;
}
</style>
